-- BuyReagentSettings
--   -Reagents
--     - {iName = ItemName, iLink = ItemLink, nStack = # of Stacks }
local MSG_HEAD, MSG_TAIL = "|cFFFF8080BuyReagent: |cFF8080FF", "|r";

function FormatMoney(money)
  local G = floor(money / 10000);
  local S = floor((money % 10000) / 100);
  local C = money % 100;

  if (G > 0) then 
    return "|r"..G.."|cFFFFFF00g|r"..S.."|cFFC0C0C0s|r"..C.."|cFFC08000c|cFF8080FF"; 
  elseif (S > 0) then 
    return "|r"..S.."|cFFC0C0C0s|r"..C.."|cFFC08000c|cFF8080FF"; 
  else
    return "|r"..C.."|cFFC08000c|cFF8080FF"; 
  end
end


local lastEvent = 0;
function BuyReagent()
  if lastEvent > 0 and time() - lastEvent < 1 then
    return;
  end
  lastEvent = time();

  local items = BuyReagentSettings.Reagents;
--  local items = Reagents[class];

--No action with SHIFT pressed
  if (IsShiftKeyDown()) then
    return;
  end

  ClearCursor();

--Search for item:Exist->Buy it->Print msg
  for i = 1,#items do
    local ItemName = items[i].iName;
    local bAccount = 0;
    local mInfo, mPrice;

    do
      for j = 1,GetMerchantNumItems() do
        mInfo, _, mPrice, mQuantity = GetMerchantItemInfo(j);
  
        if ((mInfo) and (mInfo:find(ItemName))) then
          if mQuantity > 1 then
            bAccount = items[i].nStack - math.ceil(GetItemCount(ItemName) / mQuantity);
            for k = 1, bAccount do
              BuyMerchantItem(j);
            end
          else
            local mMaxStack=GetMerchantItemMaxStack(j);
            local t = items[i].nStack * mMaxStack - GetItemCount(ItemName);
            if (t > 0) then
              for k=1,ceil(t / mMaxStack) do
                local count = floor(t / mMaxStack)~=0 and mMaxStack or t;

                BuyMerchantItem(j, count);
                t = t - mMaxStack;
                bAccount = bAccount + count;
              end;
            end
          end
          break;
        end
      end
      if (bAccount > 0) then
        print(MSG_HEAD.."Bought ["..ItemName.."]x"..bAccount.." ("..FormatMoney(bAccount*mPrice)..")"..MSG_TAIL);
      end
    end
  end

--Repair Items
  if CanMerchantRepair() and GetRepairAllCost() > 0 then
    if CanGuildBankRepair() and GetGuildBankWithdrawMoney() >= GetRepairAllCost() then
      RepairAllItems(1);
      print(MSG_HEAD.."Items Repaired from GuildBank("..FormatMoney(GetRepairAllCost())..")"..MSG_TAIL);
    else
      RepairAllItems();
      print(MSG_HEAD.."Items Repaired ("..FormatMoney(GetRepairAllCost())..")"..MSG_TAIL);
    end
  end

--Sell Poor Items
  local SellAmount = 0;
  for b=0, 4 do
    local n=GetContainerNumSlots(b);
    for s=1, n do
      local texture, itemCount = GetContainerItemInfo(b, s);
      if texture then
        local _, _, itemRarity, _, _, _, _, _, _, _, itemSellPrice = GetItemInfo(GetContainerItemLink(b, s));
        if itemRarity == 0 then
          UseContainerItem(b, s);
          SellAmount = SellAmount + itemSellPrice * itemCount;
        end
      end
    end
  end
  if SellAmount > 0 then
    print(MSG_HEAD.."Sell Poor Items:"..FormatMoney(SellAmount)..MSG_TAIL);
  end
end

local _, class=UnitClass("player")

local BRFrame =  CreateFrame("Frame")
BRFrame:RegisterEvent("ADDON_LOADED");
BRFrame:RegisterEvent("MERCHANT_SHOW");
BRFrame:SetScript("OnEvent", function(_, event, ...) 
  if event == "MERCHANT_SHOW" then 
    BuyReagent();
  elseif event == "ADDON_LOADED" then
    BuyReagentSettings = BuyReagentSettings or { Reagents= {} };
    BuyReagentSettings.Reagents = BuyReagentSettings.Reagents or {};
  end
end);

function ShowHelp() 
  print(MSG_HEAD.."BuyReagent Help:"..MSG_TAIL); 
  print("  /br add <item> <stacks>");
  print("  /br del <idx>");
  print("  /br list");
  print("|cFF8080FFMore Details on http://code.google.com/p/buyreagent/wiki/BuyReagentReadme|r")
end

SLASH_BUYREAGENT1="/br";
SlashCmdList["BUYREAGENT"] = function (msg) 
  local command, rest = msg:match("^(%S*)%s*(.-)$")
  if command == "add" then
    local item, stack = rest:match("^(.*)%s+(%d+)$")
    if item then
      itemName, itemLink = GetItemInfo(item);
      if itemName then
        for idx, r in pairs(BuyReagentSettings.Reagents) do
          if r.iName == itemName then
            r.nStack = stack;
            print (MSG_HEAD.."Modify "..r.iLink.." to "..stack.." stacks."..MSG_TAIL);
            return;
          end
        end
        table.insert( BuyReagentSettings.Reagents, { iName = itemName, iLink = itemLink, nStack = stack });
        print (MSG_HEAD.."add"..itemLink.." x "..stack..MSG_TAIL);
      else
        print(MSG_HEAD..item.." is not in local cache"..MSG_TAIL);
      end
    else
      ShowHelp()
    end
  elseif command == "del" then
    local idx = tonumber(rest:match("%d+"));
    if idx and BuyReagentSettings.Reagents[idx] then
      print (MSG_HEAD..BuyReagentSettings.Reagents[idx].iLink.." Removed."..MSG_TAIL);
      table.remove( BuyReagentSettings.Reagents, idx);
    else
      ShowHelp();
    end
  elseif command == "list" then
    print (MSG_HEAD..#BuyReagentSettings.Reagents.." reagents in List"..MSG_TAIL);
    for i=1, #BuyReagentSettings.Reagents do
      print ("  <"..i.."> "..BuyReagentSettings.Reagents[i].iLink.." x"..BuyReagentSettings.Reagents[i].nStack.." stacks.");
    end
  else
    ShowHelp();
  end
end
